<template>
  <div>
    <el-row :gutter="10">
      <el-col :span="6">
        <dashboard-card
          :icon="require('@/assets/icon/safe.png')"
          title="威胁指数"
        >
          <!-- <i class="el-icon-aim" style="margin-right: 10px; color: red"></i> -->
          <div class="emergency">
            <div class="num">{{ dashboard.today_score || 0 }}/100</div>
            <div class="progress">
              <div
                class="schedule"
                :style="{
                  width: `${((dashboard.today_score || 0.1) / 100) * 100}%`
                }"
              ></div>
            </div>
          </div>
        </dashboard-card>
      </el-col>
      <el-col :span="6">
        <dashboard-card
          :icon="require('@/assets/icon/eye.png')"
          title="行为检测计数"
        >
          <div class="behavior">
            <div class="num" @click="$router.push({ name: 'Menace_event' })">
              {{ dashboard.event_count.total }}
            </div>
            <div class="today" @click="$router.push({ name: 'Menace_event' })">
              今日：<span>{{ dashboard.event_count.today }}</span>
            </div>
          </div>
        </dashboard-card>
      </el-col>
      <el-col :span="6">
        <dashboard-card
          :icon="require('@/assets/icon/project.png')"
          title="基于 HASH 的聚合计数排行"
        >
          <el-table
            :data="dashboard.based_hash"
            :header-cell-style="{ background: '#f5f5f5' }"
            height="100"
            size="mini"
            width="100%"
          >
            <el-table-column
              label="SHA256"
              min-width="78%"
              prop="hash"
              show-overflow-tooltip
            />
            <el-table-column label="计数" min-width="22%" prop="num" />
          </el-table>
        </dashboard-card>
      </el-col>
      <el-col :span="6">
        <dashboard-card
          :icon="require('@/assets/icon/location.png')"
          title="最近 7 日异常终端"
        >
          <el-table
            :data="dashboard.unusual_host"
            :header-cell-style="{ background: '#f5f5f5' }"
            height="100"
            size="mini"
          >
            <el-table-column
              label="终端名"
              min-width="78%"
              prop="hash"
              show-overflow-tooltip
            />
            <el-table-column label="计数" min-width="22%" prop="num" />
          </el-table>
        </dashboard-card>
      </el-col>
    </el-row>
    <el-row class="mt10" :gutter="10">
      <el-col :span="10">
        <dashboard-card
          height="200"
          :icon="require('@/assets/icon/tency.png')"
          title="威胁指数趋势"
        >
          <chart-line ref="line" />
        </dashboard-card>
      </el-col>
      <el-col :span="14">
        <dashboard-card
          height="200"
          :icon="require('@/assets/icon/search.png')"
          title="最近的行为检测"
        >
          <el-table
            :data="dashboard.event_table"
            :header-cell-style="{ background: '#f5f5f5' }"
            height="200"
            size="mini"
          >
            <el-table-column label="严重程度" min-width="10%" prop="severity" />
            <el-table-column
              label="聚合计数"
              min-width="10%"
              prop="detect_count"
            />
            <el-table-column
              label="行为技术"
              min-width="30%"
              prop="technique"
            />
            <el-table-column label="检测时间" min-width="15%" prop="time" />
            <el-table-column label="终端名" min-width="20%" prop="agent_name" />
            <el-table-column label="操作" min-width="15%" prop="">
              <template slot-scope="scope">
                <el-tooltip
                  class="item"
                  :content="scope.row.detect_name"
                  effect="dark"
                  placement="top-end"
                >
                  <el-button
                    class="f12"
                    type="text"
                    @click="handleNavEventHunter(scope)"
                  >
                    详细信息
                  </el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </dashboard-card>
      </el-col>
    </el-row>
    <el-row class="mt10" :gutter="10">
      <el-col :span="24">
        <dashboard-card
          height="280"
          :icon="require('@/assets/icon/chart.png')"
          title="战术检测"
        >
          <!--          <chart-line ref="line2" />-->
          <chart-bar ref="bar" />
        </dashboard-card>
      </el-col>
    </el-row>
    <login-report v-if="showLoginReport()" ref="LoginReport" />
  </div>
</template>

<script>
import DashboardCard from "@/views/menace/components/dashboardCard";
import LoginReport from "./components/loginReport.vue";
import ChartLine from "@/components/charts/ChartLine";
import ChartBar from "@/components/charts/ChartBar";
import threat from "@/api/threat";
export default {
  name: "Dashboard",
  components: { ChartBar, ChartLine, DashboardCard, LoginReport },
  data: () => {
    return {
      num: 1,
      dashboard: {
        event_count: {},
        event_table: []
      }
    };
  },
  mounted() {
    this.initData();
  },
  destroyed() {
    this.clear();
  },
  methods: {
    handleNavEventHunter({ row: { meql_ext } }) {
      let query = Object.assign({}, meql_ext);
      delete query.limit;
      delete query.org_id;
      delete query.page;
      let route = this.$router.resolve({
        name: "Investigation_EventHunter",
        query: { ...query }
      });
      window.open(route.href);
    },
    initData() {
      threat.total().then(res => {
        res.data.based_hash = Object.keys(res.data.based_hash).map(k => {
          return { hash: k, num: res.data.based_hash[k] };
        });
        res.data.unusual_host = Object.keys(res.data.unusual_host).map(k => {
          return { hash: k, num: res.data.unusual_host[k] };
        });

        res.data.score_trend = Object.keys(res.data.score_trend).map(k => {
          let value = res.data.score_trend[k];
          return { date: k, value };
        });

        this.dashboard = res.data;
        this.drawTechBar(res.data.tech_bar);
        this.drawLine(res.data.score_trend);
        if (this.showLoginReport()) this.$refs.LoginReport.show();
        this.inserted();
      });

      setInterval(() => {
        this.num = Math.floor(Math.random() * (100 - 1) + 1);
      }, 1000);
      this.intervalId = setInterval(() => {
        if (!localStorage.getItem("loginReport")) window.location.reload();
      }, 60000);
    },
    showLoginReport() {
      if (!localStorage.getItem("loginReport")) return false;
      else return true;
    },
    clear() {
      clearInterval(this.intervalId);
    },
    drawLine(data) {
      let date = data.map(k => k.date),
        value = data.map(k => k.value);
      this.$refs.line.created({
        grid: {
          top: "3%",
          left: "10px", //默认10%
          right: "3px", //默认10%
          bottom: "3px", //默认60
          containLabel: true
        },
        xAxis: {
          type: "category",
          data: date
        },
        axisLabel: {
          show: true,
          interval: 0 //使x轴文字显示全
        },
        yAxis: {
          type: "value",
          scale: true,
          max: 100,
          min: 0,
          boundaryGap: [0.1, 0.1]
        },
        series: [
          {
            data: value,
            type: "line",
            itemStyle: {
              normal: {
                color: "#FF0000",
                lineStyle: {
                  color: "#FF0000"
                }
              }
            }
          }
        ]
      });
    },
    drawTechBar(tech_bar) {
      let barData = {
        grid: {
          left: "10px", //默认10%
          right: "10%", //默认10%
          top: "3%",
          bottom: "3px", //默认60
          containLabel: true
          //grid区域是否包含坐标轴的刻度标签
        },
        legend: {
          type: "scroll",
          left: "92%",
          right: "3px",
          orient: "vertical",
          x: "left", //可设定图例在左、右、居中
          y: "center" //可设定图例在上、下、居中
        },
        yAxis: [
          {
            type: "value"
          }
        ]
      };
      barData = Object.assign(barData, tech_bar);
      barData.series = barData.seriesData.map(k => {
        k.type = "bar";
        k.stack = "Ad";
        k.emphasis = {
          focus: "series"
        };
        return k;
      });
      barData.xAxis = { data: barData.xAxisData };
      delete barData.legendData;
      delete barData.seriesData;
      this.$nextTick(() => {
        this.$refs.bar.created(barData);
      });
    },
    inserted() {
      // 最终要显示的数字
      let finalNum = this.dashboard.event_count.total;
      let todayNum = this.dashboard.event_count.today;
      // 动画间隔
      let rate = 30;
      // 总时长
      let time = 2000;
      let time2 = 800;
      // 步长,数据增加间隔
      let step = finalNum / (time / rate);
      let step2 = todayNum / (time2 / rate);
      // 初始值
      let count = 0;
      let todayCount = 0;
      // 要保留的小数
      let timer = setInterval(() => {
        count = count + step;
        this.dashboard.event_count.total = count.toFixed(0);
        if (count > finalNum) {
          //  避免count大于finalNum最终数字显示不对
          count = finalNum;
          this.dashboard.event_count.total = count;
          // 清空定时器

          clearInterval(timer);
          timer = null;
        }
      }, rate);
      let timer2 = setInterval(() => {
        todayCount = todayCount + step2;
        this.dashboard.event_count.today = todayCount.toFixed(0);
        if (todayCount > todayNum) {
          todayCount = todayNum;
          this.dashboard.event_count.total = todayCount;
          // 清空定时器
          clearInterval(timer2);
          timer2 = null;
        }
      }, rate);
    }
  }
};
</script>

<style lang="scss" scoped>
.behavior {
  .num {
    font-size: 50px;
    font-weight: bold;
    text-align: center;
    color: red;
  }

  .today {
    padding-top: 0px;

    span {
      font-weight: bold;
      font-size: 26px;
      color: red;
    }
  }
}
.behavior:hover {
  cursor: pointer;
  background-color: #f5f5f5;
}

.emergency {
  /* position: relative; */
  padding-top: 20px;
  .progress {
    width: 100%;
    margin-inline: auto;
    background: $--color-info-light;
    height: 20px;
    .schedule {
      height: 100%;
      width: 5%;
      background-color: $--color-primary;
      transition: all 300ms;
    }
  }

  .num {
    font-size: 20px;
  }
}
</style>
